//
//  UIViewController+WKRefrer.m
//  xndm_proj
//
//  Created by Linfeng Song on 2019/12/4.
//  Copyright © 2019 Linfeng Song. All rights reserved.
//

#import "UIViewController+WKRefrer.h"
#import <objc/runtime.h>

@implementation UIViewController (WKRefrer)

+ (void)load
{
    Method setTitle = class_getInstanceMethod([self class], @selector(setTitle:));
    Method wk_setTitle = class_getInstanceMethod([self class], @selector(wk_setTitle:));
    method_exchangeImplementations(setTitle, wk_setTitle);
}


- (void)setRefererStr:(NSString *)refererStr
{
    objc_setAssociatedObject(self, @selector(refererStr),refererStr, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)refererStr
{
    NSString *referer = objc_getAssociatedObject(self, @selector(refererStr));
    return referer;
}


- (void)setCurrentRefererStr:(NSString *)currentRefererStr
{
    NSString *refererStr = self.refererStr;
    NSString *oldCurrentRefererStr = self.currentRefererStr;
    if (oldCurrentRefererStr.length > 0) {
        NSString *oldRefrerStr = [NSString stringWithFormat:@"-%@", oldCurrentRefererStr];
        if ([refererStr hasSuffix:oldRefrerStr]) {
            refererStr = [refererStr substringToIndex:refererStr.length - oldRefrerStr.length];
        }
        else if([refererStr isEqualToString:oldCurrentRefererStr])
        {
            refererStr = @"";
        }
    }
    
    if (currentRefererStr.length > 0) {
        if (refererStr.length > 0) {
            refererStr = [NSString stringWithFormat:@"%@-%@", refererStr, currentRefererStr];
        }
        else
        {
            refererStr = [NSString stringWithFormat:@"%@", currentRefererStr];
        }
    }
    self.refererStr = refererStr;
    objc_setAssociatedObject(self, @selector(currentRefererStr),currentRefererStr, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)currentRefererStr
{
    NSString *currentReferer = objc_getAssociatedObject(self, @selector(currentRefererStr));
    return currentReferer;
}


- (void)wk_setTitle:(NSString *)title
{
    [self wk_setTitle:title];
    
    self.currentRefererStr = title;
}


@end
